package com.nimlib.utils;

import android.text.TextUtils;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class NimUserInfoCache {

    private Map<String, NimUserInfo> account2UserMap = new ConcurrentHashMap<>();


    public void buildCache(){
        List<NimUserInfo> users = NIMClient.getService(UserService.class).getAllUserInfo();
        clearCache();
        addOrUpdateUsers(users,false);
    }

    public NimUserInfo getUserInfo(String account){
        if (TextUtils.isEmpty(account) || account2UserMap==null || account2UserMap.isEmpty()){
            return null;
        }
        return account2UserMap.get(account);
    }

    private void clearCache(){
        account2UserMap.clear();
    }
    private void addOrUpdateUsers(List<NimUserInfo> users,boolean notify){
        if (users==null || users.isEmpty())return;
        for (NimUserInfo u : users) {
            account2UserMap.put(u.getAccount(),u);
        }
    }

    /**
     * ************************************ 单例 **********************************************
     */

    public static NimUserInfoCache getInstance() {
        return InstanceHolder.instance;
    }
    static class InstanceHolder {

        final static NimUserInfoCache instance = new NimUserInfoCache();
    }

}
